package com.bdqn.myInterceptor;
import com.bdqn.util.HttpUtils;
import com.bdqn.entity.util.RespBean;
import com.bdqn.entity.util.ResultEnum;
import com.bdqn.util.BaseException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ExceptionInterceptor implements HandlerInterceptor {
    /**
     * 重写最终执行的方法  来处理异常
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    private  final Logger logger = LoggerFactory.getLogger(ExceptionInterceptor.class);
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //打印请求路径
        logger.info("URI:{}",request.getRequestURI());
        //处理异常信息
        RespBean result = null;
        if(ex !=null){
            logger.info("异常信息：{}", ex);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            if(ex instanceof BaseException){
                BaseException baseEx = (BaseException) ex;
                result = new RespBean(baseEx.getResultEnum());
            }else{
                result = new RespBean(ResultEnum.COMMON_EXCEPTION);
            }
            //向客户端返回json数据
            HttpUtils.outputJson(response,result);
        }

    }
}
